'use client';

import { useClerk, useUser } from '@clerk/nextjs';
import Spline from '@splinetool/react-spline';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useEffect } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import usePageViewLog from '@/hooks/usePageViewLog';
import { GiftIcon, MusicIcon } from '@/icons';
import { components } from '@/lib/gen';
import { SMALL_IMAGE } from '@/utils/constants';
import { PageEventType, eventLogger } from '@/utils/event-logger';
import { getClerkSignUpRedirectProps } from '@/utils/utils';

import { getInviterHandle } from '../utils';

const InvitePageClient = ({
  profile,
}: {
  profile: components['schemas']['SimpleProfileInfoSchema'];
}) => {
  const { user } = useUser();
  const { session } = useStores();
  const router = useRouter();
  const clerk = useClerk();
  const searchParams = useSearchParams();
  const pathname = usePathname();

  const source = searchParams.get('source');
  const inviterHandle = getInviterHandle(pathname);
  usePageViewLog({
    actionName: 'PageViewed',
    componentContext: 'invite',
    context: {
      inviterHandle: inviterHandle || '',
      source: source || '',
    },
  });

  useEffect(() => {
    // On page load, try to create an InviteHistory record in the db
    // if the user is signed in
    handleGrantCredits();

    const handleBeforeUnload = (event: any) => {
      // event.preventDefault(); // With this commented out, the page won't ask to confirm exiting the page
      event.returnValue = '';

      const inviterHandle = getInviterHandle(pathname);
      eventLogger.logWebPageEvent({
        userId: session.userId || '',
        eventType: PageEventType.CLOSE,
        element: 'invitee_page',
        secondaryElement: source,
        entityId: inviterHandle,
        entityType: 'inviter_handle',
        pageUrl: pathname,
      });
    };
    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, []);

  const handleGrantCredits = () => {
    const handle = getInviterHandle(pathname);

    if (handle !== null) {
      // this will basically just log a message but return normally if inviter
      // handle doesn't exist
      // If the user is signed in, make a request to check
      // if the user has already been invited (a record exists in InviteHistory).
      // If not, create a record in InviteHistory.
      const result = session.grantInviteCredits(handle);
      if (process.env.NODE_ENV === 'development') {
        console.log(result);
      }
    }
  };

  const redirectToInvitePage = () => {
    const handle = getInviterHandle(pathname);

    eventLogger.logWebPageEvent({
      userId: session.userId || '',
      eventType: PageEventType.CLICK,
      element: 'invitee_page',
      secondaryElement: 'accept_invite_button',
      entityId: handle,
      entityType: 'inviter_handle',
      pageUrl: pathname,
    });

    if (handle !== null) {
      clerk.openSignUp({
        ...getClerkSignUpRedirectProps(`/invite/@${handle}/`),
      });
    }

    setTimeout(handleGrantCredits, 5000);
  };

  return user ? (
    <div className='mt-[200px] flex w-full flex-col items-center'>
      <div className='mt-4 text-center font-sans text-xl text-white'>
        You are already signed in.
      </div>
      <Button
        variant={ButtonVariant.Primary}
        size={ButtonSize.Large}
        shape={ButtonShape.Rounded}
        icon={MusicIcon}
        onClick={() => router.push('/create')}
        className='m-4'
      >
        Create a song
      </Button>
    </div>
  ) : (
    <div className='mt-[10vh] flex w-full flex-col items-center'>
      <h1 className='max-w-full font-serif text-[28px] font-light text-foreground-primary lg:text-[40px]'>
        You&apos;re Invited to Suno
      </h1>
      <div className='relative mb-8 flex items-center'>
        <p className='mr-2 text-center font-sans text-sm text-white'>
          Sign up and make 10 songs to earn (and gift) 250 free credits!
        </p>
      </div>

      <Button
        variant={ButtonVariant.Aura}
        shape={ButtonShape.Rounded}
        size={ButtonSize.Large}
        icon={GiftIcon}
        onClick={redirectToInvitePage}
        backgroundImage='https://cdn1.suno.ai/invite-button-gradient.png'
      >
        Accept Invite
      </Button>
      <div className='mt-4 h-1/2 w-full md:max-w-200'>
        <Spline scene='https://prod.spline.design/92ma35dT8aeks7Tq/scene.splinecode' />
      </div>
      <div>
        <p className='mt-6 text-center font-sans text-sm'>
          Sent from @{inviterHandle}
        </p>
        <div className='relative mx-auto my-4 aspect-square h-auto w-12 rounded-full'>
          <button
            onClick={() => {
              eventLogger.logWebPageEvent({
                userId: session.userId || '',
                eventType: PageEventType.CLICK,
                element: 'invitee_page',
                secondaryElement: 'inviter_avatar',
                entityId: inviterHandle,
                entityType: 'inviter_handle',
                pageUrl: pathname,
              });
              router.push(`/@${inviterHandle}`);
            }}
          >
            <ImageWithFallback
              className='aspect-square h-auto w-full rounded-full object-cover'
              imageSize={SMALL_IMAGE}
              width={224}
              height={224}
              alt={`@${inviterHandle}`}
              src={profile?.avatar_image_url || ''}
              style={{ position: 'relative' }}
            />
          </button>
        </div>
      </div>
    </div>
  );
};

export default InvitePageClient;
